<template>
  <div class="dd-class">
      <el-card style="width: 15%; margin-bottom: 10px">

      </el-card>
  </div>
  <div class="dashboard-3d-container">
    <div ref="threeContainer" class="three-canvas"></div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue'
import * as THREE from 'three'
import {FBXLoader} from 'three/examples/jsm/loaders/FBXLoader'
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'

const threeContainer = ref<HTMLDivElement | null>(null)

onMounted(() => {
  if (!threeContainer.value) return

  const scene = new THREE.Scene()
  scene.background = new THREE.Color(0x222233)

  const width = threeContainer.value.clientWidth
  const height = 600
  const camera = new THREE.PerspectiveCamera(45, width / height, 1, 2000)
  camera.position.set(100, 200, 300)

  const renderer = new THREE.WebGLRenderer({antialias: true})
  renderer.setSize(width, height)
  threeContainer.value.appendChild(renderer.domElement)

  const controls = new OrbitControls(camera, renderer.domElement)
  controls.target.set(0, 100, 0)
  controls.update()

  scene.add(new THREE.AmbientLight(0xffffff, 0.5))
  const dirLight = new THREE.DirectionalLight(0xffffff, 1)
  dirLight.position.set(1, 1, 1).normalize()
  scene.add(dirLight)

  // FBXLoader
  const loader = new FBXLoader()
  loader.load('/model/monster.fbx', (object) => {
        console.log('FBX loaded:', object)
        object.scale.set(1, 1, 1)
        object.position.set(0, 0, 0)
        scene.add(object)
        const mixer = new THREE.AnimationMixer(object)
        if (object.animations && object.animations.length > 0) {
          const action = mixer.clipAction(object.animations[0])
          action.play()
        }
        const clock = new THREE.Clock()

        function animate() {
          requestAnimationFrame(animate)
          const delta = clock.getDelta()
          mixer.update(delta)
          renderer.render(scene, camera)
        }

        animate()
      },
      undefined,
      (error) => {
        console.error('FBXLoader error:', error)
        alert('FBX模型加载失败，请检查路径和文件名！')
      })

  window.addEventListener('resize', () => {
    const w = threeContainer.value?.clientWidth || 1200
    camera.aspect = w / height
    camera.updateProjectionMatrix()
    renderer.setSize(w, height)
  })
})
</script>

<style scoped>
.dd-class {

}

.dashboard-3d-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  background: #222233;
  padding: 0;
}

.three-canvas {
  width: 100%;
  max-width: 1200px;
  height: 600px;
  margin: 0 auto 30px auto;
  border-radius: 12px;
  box-shadow: 0 4px 32px #000a;
  background: #222233;
}
</style>
